package utils;

public class ReadWriteCritical
{
    // 1 for read available, 2 for write available
    private int state = 2;

    public synchronized void getReadLock()
    {
        if (state == 2)
        {
            try
            {
                wait();
            }
            catch (Exception e)
            {}
        }
        state = 1;
    }

    public synchronized void getWriteLock()
    {
        if (state == 1)
        {
            try
            {
                wait();
            }
            catch (Exception e)
            {}
        }
        state = 2;
    }

    public synchronized void releaseReadLock()
    {
        if (state == 1)
        {
            state = 2;
        }
        notify();
    }

    public synchronized void releaseWriteLock()
    {
        if (state == 2)
        {
            state = 1;
        }
        notify();
    }
}
